<template>
  <MainSlot>
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" :unfoldFlag="unfoldFlag" @search="search"
        @isUnfold="(v) => { unfoldFlag = v }">
      </SearchForm>
    </template>
    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:table>
      <TableData class="table" :config="table_config" :configFixed="{ flag: 'right' }" :tableThead="tableThead"
        v-loading="loading" :dataList="dataList" @selection-change="selectionChange">
        <!-- <template v-slot:showEcharts="{ row }">
          <span class="successText" @click="deadCount(row.diseaseRecordsId, row)">查看</span>
        </template> -->
        <template v-slot:completeDate="{ row }">
          {{ row.completeDate ? '已完成' : '未完成' }}
        </template>
      </TableData>
      <!-- <div class="content" v-loading="loading">
        <div class="echarts" v-loading="deadCountLoading" :class="isOpenEchart ? 'openEcharts' : 'echarts'">
          <div class="deadInfo">
            <div class="openEchart" title="展开/收起" @click="openEcharts">
              <i v-show="!isOpenEchart" class="el-icon-caret-left"><span>
                  展开
                </span></i>
              <i v-show="isOpenEchart" class="el-icon-caret-right">
                <span>收起</span>
              </i>
            </div>
            <div class="info">疾病名称：<span>{{ chooseDeadInfo.diseaseName }}</span></div>
            <div class="info">发现人：<span>{{ chooseDeadInfo.findName }}</span></div>
            <div class="info">发现日期：<span>{{ chooseDeadInfo.findDate }}</span></div>
          </div>
          <div class="lineEcharts">
            <LineEcharts v-if="!deadCountLoading" :seriesData="seriesData" :xAxis="xAxis"
              :formatterInfo="formatterInfo">
            </LineEcharts>
          </div>
        </div>
      </div> -->
    </template>
    <template v-slot:pagination>
      <Pagination @current-change="handleCurrentChange" :page="page" :total="total">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <AddEdit :title="'疾病诊断'" :batchList="batchList" :fishPondList="fishPondList"
        :staffList="staffList" @closeDialog="closeDialog" :materialList="materialList" :diseaseList="diseaseList"
        :addEditFlag="addEditFlag" :dialogVisible="dialogVisible" :data="formData">
      </AddEdit>
    </template>
  </MainSlot>
</template>
<script>
import store from "@/store";
import MainSlot from "@/components-production-management/MainSlot";
import Pagination from '@/components-production-management/Pagination';
import SearchForm from '@/components-production-management/SearchForm';
import TableData from '@/components-production-management/TableData';
import BtnSlot from '@/components-production-management/BtnSlot';
import EnumSlot from '@/components-production-management/EnumSlot';
import AddEdit from './components/addEdit.vue';
import LineEcharts from '@/components-production-management/LineEcharts'

//疾病记录
import diseaseRecords from '@/api/disease-prevention-and-control/disease-records-nc.js';
//获取员工
import staffApi from "@/api/basic-info-manage/staff";
//疾病
import diseaseManagement from '@/api/disease-prevention-and-control/characteristic-management.js';
//药品
import MaterialApi from "@/api/basic-info-manage/material";

//NC批次
import ncproductionApi from "@/api/production-management-nc/index";
import ncbasicinfoApi from "@/api/nc-basic-info/index";
export default {
  components: { MainSlot, Pagination, SearchForm, TableData, BtnSlot, EnumSlot, AddEdit, LineEcharts },
  data() {
    return {
      isOpenEchart: false,
      deadCountLoading: false,
      unfoldFlag: false,
      loading: false,
      dialogVisible: false,
      dialogVisible_lookView: false,
      addEditFlag: 'add',
      selectList: [],
      unitList: [],
      formData: {},
      page: 1,
      total: 10,
      selectIndex: 0,
      searchFormData: {},
      btnList: ['add', 'delete'],
      dataList: [],
      tableThead: [
        { isShow: true, label: '疾病名称', prop: 'diseaseName', minWidth: '150' },
        { isShow: true, label: '养殖鱼塘', prop: 'fishPondName' },
        // { isShow: true, label: '批次编号', prop: 'batchName' },
        { isShow: true, label: '称重品种', prop: 'varietyName' },
        { isShow: true, label: '病鱼数', prop: 'num', minWidth: '60' },
        { isShow: true, label: '状态', slotName: 'completeDate', minWidth: '60' },
        // { isShow: true, label: '直鱼趋势', slotName: 'showEcharts' },
        { isShow: true, label: '发现人', prop: 'findName' },
        { isShow: true, label: '发现日期', prop: 'findDate', minWidth: '200' }
      ],
      // 配置项
      table_config: {
        isCheckBox: true,
        isOperation: true,
        // 表格操作列
        operation: {
          label: '操作',
          width: '190',
          cols: [
            {
              label: '继续处理',
              type: 'text',
              flag: 'addAgain',
              handleRow: this.handleRow
            },
            {
              label: '编辑',
              type: 'text',
              flag: 'edit',
              handleRow: this.handleRow
            },
            {
              label: '完成',
              type: 'text',
              flag: 'complete',
              class: 'warningText',
              handleRow: this.handleRow
            },
            {
              label: '删除',
              type: 'text',
              flag: 'del',
              class: 'errorText',
              handleRow: this.handleRow
            }
          ]
        },
      },
      formItemList: [
        {
          label: '养殖鱼塘',
          type: 'select',
          selectOptions: [],
          param: 'fishPondName',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '养殖品种',
          type: 'select',
          selectOptions: [],
          param: 'varietyName',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '疾病名称',
          type: 'select',
          selectOptions: [],
          param: 'diseaseName',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '发现人',
          type: 'select',
          selectOptions: [],
          param: 'findNameId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '发现日期',
          type: 'datetimerange',
          param: 'dateTime',
          multiple: false,
          isShow: true
        },
      ],
      fishPondList: [],
      batchList: [],
      allbatchList: [],
      staffList: [],
      materialList: [],
      fishVarietyList: [],
      breedTypeList: [],
      diseaseList: [],
      breedTypeObj: {},
      chooseDeadInfo: {},
      xAxis: [],
      seriesData: [],
      formatterInfo: [],
    }
  },
  mounted() {
    this.queryPageByCondition();
    this.initData();
  },

  computed: {
    materialObj() {
      return store.state.basicData.material;
    }
  },
  methods: {
    async initData() {
      let { data: diseaseList } = await diseaseManagement.queryByCondition({});
      let { data: materialList } = await MaterialApi.queryByCondition({ materialTypeNo: 'DRUG' }) //物料
      let { data: staffList } = await staffApi.queryByCondition();
      let { data: fishPondList } = await ncproductionApi.queryInputPond({});
      let { data: fishVarietyList } = await ncbasicinfoApi.queryMaterial({ pk_parent: "1001A110000000003G58" }); //品种
      this.staffList = staffList || [];
      this.fishPondList = fishPondList || [];
      this.fishVarietyList = fishVarietyList || [];
      this.diseaseList = diseaseList || [];
      this.fishPondList = this.fishPondList.map(item => {
        return {
          ...item,
          pondName: item.cwarehousename,
        }
      })
      this.fishVarietyList = this.fishVarietyList.map(item => {
        return {
          ...item,
          varietyName: item.name,
        }
      })
      this.allbatchList = this.fishPondList.map(item => {
        return {
          ...item,
          batchName: item.vproductbatch,
        }
      })
      this.materialList = materialList;
      this.setFormOptions();
    },
    //初始化数据
    // async initData() {
    // let { data: materialList } = await MaterialApi.queryByCondition({ materialTypeNo: 'DRUG' }) //物料
    // let { data: batchList } = await batchManagement.queryByCondition({ unCompleteBatch: true });//查询批次列表
    // let { data: allbatchList } = await batchManagement.queryByCondition();
    // let { data: fishVarietyList } = await fishVarietyApi.queryByCondition();//查询品种


    // let { data: fishPondList } = await fishPondApi.queryByCondition({ bindBatch: true });//查询鱼塘列表 //bindBatch:true 查询绑定了批次的鱼塘
    // this.fishPondList = fishPondList || [];
    // this.batchList = batchList || [];
    // this.allbatchList = allbatchList || [];
    // this.fishVarietyList = fishVarietyList || [];
    //   this.materialList = materialList || [];
    //   this.setFormOptions();
    // },
    setFormOptions() {
      let list = JSON.parse(JSON.stringify(this.formItemList));
      this.formItemList = []
      list.forEach((item, index) => {
        if (item.param.indexOf('fishPondName') !== -1) {
          let selectOptions = this.fishPondList.map(data => {
            return {
              text: data.pondName, value: data.pondName
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param.indexOf('diseaseName') !== -1) {
          let selectOptions = this.diseaseList.map(data => {
            return {
              text: data.diseaseName, value: data.diseaseName
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param.indexOf('varietyName') !== -1) {
          let selectOptions = this.fishVarietyList.map(data => {
            return {
              text: data.varietyName, value: data.varietyName
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param.indexOf('findNameId') !== -1) {
          let selectOptions = this.staffList.map(data => {
            return {
              text: data.staffName, value: data.staffId
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param.indexOf('batchName') !== -1) {
          let selectOptions = this.allbatchList.map(data => {
            return {
              text: data.batchName, value: data.batchName
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };

      });
      this.$nextTick(() => {
        this.$set(this, 'formItemList', list)
        console.log(this.formItemList)
      })
    },
    //批量删除
    delList(deleteList = [], key = 'diseaseRecordsId') {
      let list = []
      deleteList.forEach(item => {
        list.push(item[key])
      })
      console.log(list)
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await diseaseRecords.delListById(list);
        if (res.success) {
          this.$message.success(res.message || '删除成功');
          this.queryPageByCondition();
        } else {
          this.$message.warning(res.message || '删除失败');
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //完成疾病
    completeDisease(id) {
      diseaseRecords.completeDisease(id).then(res => {
        if (res.success) {
          this.queryPageByCondition();
          this.$message.success('操作成功')
        } else {
          this.$message.warning(res.message || '操作失败')
        }
      })
    },
    //直鱼趋势
    deadCount(diseaseRecordsId, row = {}) {
      if (this.deadCountLoading) {
        this.$message.warning('数据加载中请稍后查看!')
      } else {
        this.deadCountLoading = true;
        this.chooseDeadInfo = row;
        diseaseRecords.deadCount(diseaseRecordsId).then(res => {
          this.deadCountLoading = false;
          if (res.success) {
            let { data } = res;
            this.seriesData = data.map(item => { return item.num || 0 });
            this.xAxis = data.map(item => { return item.date });
            this.formatterInfo = data.map(item => {
              let list = []
              item.diseaseDealDetailList && item.diseaseDealDetailList.forEach(info => {
                list.push(
                  `${info.materialName}：${info.amount}${this.materialObj[info.materialId].unit || ''}`
                )
              })
              return list
            });
          } else {
            this.xAxis = [];
            this.seriesData = [];
            this.formatterInfo = [];
            this.$message.warning(res.message);
          }
        }).catch(er => {
          this.deadCountLoading = false;
        })
      }
    },
    //查询
    queryPageByCondition() {
      let params = {
        page: this.page,
        size: 10,
        entity: {
          ...this.searchFormData
        }
      }
      this.loading = true;
      diseaseRecords.queryPageByCondition(params).then(res => {
        this.loading = false;
        if (res.success == 1) {
          this.dataList = res.data.content || [];
          this.total = res.data.totalElements;
          if (res.data.totalPages && this.page > res.data.totalPages) {
            this.page = res.data.totalPages;
            this.queryPageByCondition();
          };
          // if (this.dataList.length > 0) {
          //   this.deadCount(this.dataList[0].diseaseRecordsId, this.dataList[0])
          // };
          // this.openEchart = true;
        } else {
          this.$message.warning(res.message || '分页查询失败')
        }
      }).catch(err => {
        this.loading = false;
        console.log(err)
      })
    },
    //搜索
    search(data) {
      this.page = 1;
      let endData = null;
      let startData = null;
      if (data.dateTime && data.dateTime.length == 2) {
        startData = data.dateTime[0];
        endData = data.dateTime[1];
      }
      this.searchFormData = {
        ...this.searchFormData,
        ...data,
        dealEndDate: endData,
        dealStartDate: startData
      };
      this.queryPageByCondition();
    },
    //翻页查询
    handleCurrentChange(page) {
      this.page = page;
      this.queryPageByCondition();
    },
    openEcharts() {
      this.isOpenEchart = !this.isOpenEchart;
      this.deadCountLoading = true;
      setTimeout(() => {
        this.$nextTick(() => {
          this.deadCountLoading = false;
        })
      }, 300)
    },
    //查看详情
    lookView(row) {
      console.log(row)
      this.dialogVisible_lookView = true;
    },
    // table操作方法
    handleRow(rowData, item) {
      if (rowData.inputPondId) {
        this.$message.warning('该记录已使用')
        return
      }
      if (item.flag == 'edit') {
        this.dialogVisible = true;
        this.formData = JSON.parse(JSON.stringify(rowData))
      } else if (item.flag == 'del') {
        this.delList([rowData]);
      } else if (item.flag == 'addAgain') {
        this.dialogVisible = true;
        this.formData = JSON.parse(JSON.stringify(rowData))
      } else if (item.flag == 'complete') {
        this.completeDisease(rowData.diseaseRecordsId)
      }
      this.addEditFlag = item.flag
    },
    // 多选方法
    selectionChange(val) {
      this.selectList = val || []
    },
    //获取选中Btn
    getBtnEvent(flag) {
      if (flag == 'add') {
        this.formData = { medicineList: [{ convertNum: null, amount: null, materialId: null, materialName: null }] };
        this.dialogVisible = true
      } else if (flag == 'delete') {
        if (this.selectList.length > 0) {
          this.delList(this.selectList)
        } else {
          this.$message.warning('请先选择表单数据项后再删除！')
        }
      }
      this.addEditFlag = flag
    },
    //关闭弹窗
    closeDialog() {
      this.dialogVisible = false;
      this.queryPageByCondition();
    },
  }
};
</script>
<style lang="scss" scoped>
.content {
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: space-between;
  flex-wrap: nowrap;

  .table {
    width: 60%;
    transition: all 0.3s;
  }

  .closeTable {
    width: 0;
    overflow: hidden;
  }

  .echarts {
    padding: 20px;
    width: calc(40% - 15px);
    height: 100%;
    background-color: #f6f6f6;
    border: 1px solid #f8f8f8;
    transition: all 0.3s;

    .openEchart {
      font-size: 14px;
      color: rgb(3, 166, 231);
      cursor: pointer;

      span {
        font-size: 14px;
      }
    }

    .deadInfo {
      color: #333333;
      line-height: 26px;
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;

      span {
        color: rgb(3, 166, 231);
      }
    }


    .lineEcharts {
      height: calc(100% - 50px);
      overflow: hidden;
    }
  }

  .openEcharts {
    width: 100%;
    height: 100%;
  }
}
</style>